package com.yangcsoft.modules.deptmanage.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.yangcsoft.common.utils.DateUtils;
import com.yangcsoft.common.utils.ExcelUtil;
import com.yangcsoft.common.validator.ValidatorUtils;
import com.yangcsoft.modules.sys.service.SysDictService;
import com.yangcsoft.modules.sys.shiro.ShiroUtils;
import org.apache.commons.io.IOUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

import com.yangcsoft.modules.deptmanage.entity.ContractInfoEntity;
import com.yangcsoft.modules.deptmanage.service.ContractInfoService;
import com.yangcsoft.common.utils.PageUtils;
import com.yangcsoft.common.utils.R;


/**
 * 合同信息表
 *
 * @author XueQing Wang
 * @email 17621152225@163.com
 * @date 2019-05-02 14:22:44
 */
@RestController
@RequestMapping("deptmanage/contractinfo")
public class ContractInfoController {
    @Autowired
    private ContractInfoService contractInfoService;
    @Autowired
    private SysDictService sysDictService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("deptmanage:contractinfo:list")
    public R list(@RequestParam Map<String, Object> params) {
        String key = "";
        Object keyObj = params.get("key");
        if (keyObj != null) {
            key = keyObj.toString();
        }
        params.put("key" , key);
        PageUtils page = contractInfoService.queryPage(params);

        return R.ok().put("page" , page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{contractNo}")
    @RequiresPermissions("deptmanage:contractinfo:info")
    public R info(@PathVariable("contractNo") Integer contractNo) {
        ContractInfoEntity contractInfo = contractInfoService.selectById(contractNo);

        return R.ok().put("contractInfo" , contractInfo);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("deptmanage:contractinfo:save")
    public R save(@RequestBody ContractInfoEntity contractInfo) {
        contractInfo.setCreateDate(DateUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
        contractInfo.setCreateUser(ShiroUtils.getUserEntity().getUsername());
        contractInfoService.save(contractInfo);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("deptmanage:contractinfo:update")
    public R update(@RequestBody ContractInfoEntity contractInfo) {
        ValidatorUtils.validateEntity(contractInfo);
        contractInfo.setUpdateDate(DateUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
        contractInfo.setUpdateUser(ShiroUtils.getUserEntity().getUsername());
        contractInfoService.updateAllColumnById(contractInfo);//全部更新

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("deptmanage:contractinfo:delete")
    public R delete(@RequestBody Integer[] contractNos) {
        contractInfoService.deleteBatchIds(Arrays.asList(contractNos));

        return R.ok();
    }

    /**
     * 导出报表
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/export")
    public R export(Long[] ids, HttpServletResponse response, HttpServletRequest request) {
        String[] secondTitles = null;
        String[] beanProperty = null;
        String title = null;
        secondTitles = new String[]{
                "合同序号" ,
                "合同名称" ,
                "合同简介" ,
                "合同类型（人力，项目）" ,
                "合同总金额" ,
                "合同状态（签订，未签订）" ,
                "公司序号" ,
                "客户序号" ,
                "付款总节点数量" ,
                "付款节点序号" ,
                "付款节点金额" ,
                "付款节点状态" ,
                "创建日期" ,
                "创建人" ,
                "修改日期" ,
                "修改人"
        };
        beanProperty = new String[]{
                "contractNo" ,
                "contractName" ,
                "contractInfo" ,
                "contractType" ,
                "contractMoney" ,
                "contractStatus" ,
                "companyNo" ,
                "customerNo" ,
                "payAllItemCount" ,
                "payItemNo" ,
                "payItemMoney" ,
                "payItemStatus" ,
                "createDate" ,
                "createUser" ,
                "updateDate" ,
                "updateUser"
        };
        title = "合同信息表报表";

        List<ContractInfoEntity> list = contractInfoService.selectList(new EntityWrapper<>());
        Map<String,String> contractTypes = sysDictService.selectExportDictMap("contractType");
        Map<String,String> contractStatus = sysDictService.selectExportDictMap("contractStatus");
        Map<String,String> payItemStatus = sysDictService.selectExportDictMap("payItemStatus");
        for (ContractInfoEntity entity : list) {
            entity.setPayItemStatus(payItemStatus.get(entity.getPayItemStatus()));
            entity.setContractType(contractTypes.get(entity.getContractType()));
            entity.setContractStatus(contractStatus.get(entity.getContractStatus()));
        }

        File file = ExcelUtil.exportResult(request, list, title, secondTitles, beanProperty);
        try {
            response.setContentType("application/x-download");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(title.getBytes("gbk"), "iso8859-1") + ".xls");
            ServletOutputStream outputStream = response.getOutputStream();
            FileInputStream fileInputStream = new FileInputStream(file);
            IOUtils.copy(fileInputStream, outputStream);
            outputStream.close();
            fileInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return R.ok();
    }

    /**
     * 导入报表
     *
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/batchImport")
    public R batchImport(HttpServletResponse response, MultipartFile file) throws Exception {
        String[] beanProperty = null;
        beanProperty = new String[]{
                "contractName" ,
                "contractInfo" ,
                "contractType" ,
                "contractMoney" ,
                "contractStatus" ,
                "companyNo" ,
                "customerNo" ,
                "payAllItemCount" ,
                "payItemNo" ,
                "payItemMoney" ,
                "payItemStatus"
        };
        List<ContractInfoEntity> list = ExcelUtil.parserExcel(ContractInfoEntity.class, file, beanProperty);
        Map<String,String> contractTypes = sysDictService.selectDictMap("contractType");
        Map<String,String> contractStatus = sysDictService.selectDictMap("contractStatus");
        Map<String,String> payItemStatus = sysDictService.selectDictMap("payItemStatus");
        for (ContractInfoEntity entity : list) {
            entity.setPayItemStatus(payItemStatus.get(entity.getPayItemStatus()));
            entity.setContractType(contractTypes.get(entity.getContractType()));
            entity.setContractStatus(contractStatus.get(entity.getContractStatus()));
            save(entity);
        }
        return R.ok();
    }

    /**
     * 下载导入模版
     */
    @RequestMapping("/templateDownload")
    public R exportXls(HttpServletResponse response) {
        String title = "合同信息表录入模版";
        String[] secondTitles = new String[]{
                "合同名称" ,
                "合同简介" ,
                "合同类型（人力，项目）" ,
                "合同总金额" ,
                "合同状态（签订，未签订）" ,
                "公司序号" ,
                "客户序号" ,
                "付款总节点数量" ,
                "付款节点序号" ,
                "付款节点金额" ,
                "付款节点状态"
        };

        Integer startRow = 0;
        Integer endRow = 0;
        Integer startCol = 0;
        Integer endCol = 0;

        HSSFWorkbook workbook = ExcelUtil.createWorkBook(response,title,title,secondTitles);
        workbook = ExcelUtil.setValidationCell(workbook, sysDictService.selectDictListByCode("contractType"),1,100,2,2);
        workbook = ExcelUtil.setValidationCell(workbook, sysDictService.selectDictListByCode("contractStatus"),1,100,4,4);
        ExcelUtil.templateDownload(response,workbook,secondTitles,startRow,endRow,startCol,endCol);
        return R.ok();
    }

}
